
//Copyright 1997-2009 Syrinx Development, Inc.
//This file is part of the Syrinx Web Application Framework (SWAF).
// == BEGIN LICENSE ==
//
// Licensed under the terms of any of the following licenses at your
// choice:
//
//  - GNU General Public License Version 3 or later (the "GPL")
//    http://www.gnu.org/licenses/gpl.html
//
//  - GNU Lesser General Public License Version 3 or later (the "LGPL")
//    http://www.gnu.org/licenses/lgpl.html
//
//  - Mozilla Public License Version 1.1 or later (the "MPL")
//    http://www.mozilla.org/MPL/MPL-1.1.html
//
// == END LICENSE ==
using System;
using System.Collections;
using System.Text;
using System.IO;

using Swaf;
using Swaf.BizObj;
using Swaf.BizRule;
using Swaf.Container;

namespace Syrinx
{
	/// <summary>
	/// this class should always be called in the local server 
	/// </summary>
	public class ThemeBizRule : BaseBizRules
	{
		/// <summary>
		/// This method is a post extends bizrule of the UserManagement getCompany bizrule, which retrieves 
		/// the theme name that is assigned for the company and returns it to any calling client.
		/// This is responsible for setting  the company theme name by retrieving the company them
		/// name information from the database based on the company id and setting this value on the
		/// company themeName field which is injected by the Gallery feature defination.
		/// Themes can be implemented for companies as branding
		/// </summary>
		/// <param name="app"></param>
		/// <param name="context"></param>
		/// <param name="returnValue">bizObj returned by the bizrule that this extends</param>
		/// <param name="inputParams">parmeters of the bizrule that this extends</param>
		/// <returns></returns>
		public IBizObj getCompanyThemeName(IApplication app, IRuleContext context, object returnValue, object[] inputParams)
		{
			try
			{
				IBizObj company = returnValue as IBizObj;
				if (returnValue != null)
				{
					IBizObj settings = app.appData.get("DA.Syrinx.GetCompanyTheme", company) as IBizObj;
					company.put("settings.themeName", settings.get("themeName"));
					company.put("appThemes", getCompanyThemes(app, context));
				}
				return company;
			}
			catch (Exception e)
			{
				throw new SyrinxException("Error executing getCompanyThemeName", e);
			}
		}

		public IBizObjList getCompanyThemes(IApplication app, IRuleContext context)
		{
			string path = Path.Combine(app.appData.get("baseDir").ToString(), "App_Themes");
			DirectoryInfo di = new DirectoryInfo(path);

			IBizObjList themes = app.bizObjMgr.createList("Theme");
			 
			IBizObj obj = themes.insertNew();
			obj.put("name","");
			if(di.Exists)
				foreach (DirectoryInfo dir in di.GetDirectories())
					if (!dir.Name.StartsWith("."))
					{
						obj = themes.insertNew();
						obj.put("name", dir.Name);
					}
			return themes;
		}

		public string getCompanyTemplateName(IApplication app, IRuleContext context, IBizObj company)
		{
			string template = "UserManagement.AspNet.CompanyDisplay";
			if (company != null && company.containsField("themeName"))
				template += ",Syrinx.Gui.AspNet.CompanyThemeDisplay";
			return template;
		}

		public void setCompanyThemeSetting(IApplication app, IRuleContext context, IBizObj company)
		{
			try
			{
				if (company == null)
					throw new SyrinxException("error executing updateCompanyTheme bizrule. required parameter is null.");
				if (company.get("settings.themeName").ToString().Length > 0)
				{
					app.appData.put("DA.Syrinx.UpdateCompanyTheme", company);
					if (!(bool)company.get("settings.canUserSelectTheme") && company.get("id").Equals(ActiveCompanyId))
					{
						//TODO: This code needs to be much better than this.  It only changes the current user, not all other 
						//user's currently using the site.  It needs to be rewritten to update all users logged into the application
						//for the same company.
						CurrentUser.put("settings.themeName", company.get("settings.themeName"));
					}
				}
			}
			catch (Exception e)
			{
				throw new SyrinxException("error executing setCompanyTheme.", e);
			}
		}
		public void updateCompanyTheme(IApplication app, IRuleContext context, object returnValue, object[] inputParams)
		{
			try
			{
				IBizObj company = inputParams[2] as IBizObj;
				setCompanyThemeSetting(app, context, company);
			}
			catch (Exception e)
			{
				throw new SyrinxException("error executing updateCompanyTheme.", e);
			}

		}

		/// <summary>
		/// this rule is called as a post execute from the UserLogin.getUserPreferences bizRule.
		/// </summary>
		/// <param name="app"></param>
		/// <param name="context"></param>
		/// <param name="returnValue"></param>
		/// <param name="inputParams"></param>
		public object setUserPrefences(IApplication app, IRuleContext context, object returnValue, object[] inputParams)
		{
			IBizObj userSettings = returnValue as IBizObj;
			Swaf.BGuid.Guid userId = inputParams[2] as Swaf.BGuid.Guid;
			IResults rc = context.RuleGroup.execute(context, "getUserCompanyId", userId);
			Swaf.BGuid.Guid companyId = rc.CallResults as Swaf.BGuid.Guid;
			context.put("id", companyId);
			IBizObj companySettings = app.appData.get("DA.Syrinx.GetCompanyTheme", context) as IBizObj;
			if(companySettings != null)
				userSettings.put("themeName", companySettings.get("themeName"));
			return userSettings;
		}

		public string getMessageTemplate(IApplication app, IRuleContext context, IBizObj bizobj)
		{
			if (bizobj != null)
				return "Syrinx.Gui.AspNet.MessageDisplay";
			return "";
		}
	}
}
